#!/usr/bin/bash
#start scripts
local_start_scripts="${WORKSPACE}/huixingkj/tools/prod"
remote_start_scripts_dir="/data/scripts"
start_scripts="release.sh"


#projectname
project_name=`echo $1 | awk -F '_' '{print $2}'`
release_ip_all=$2
type=$3

java_opts=`echo ${@:4}`

echo $java_opts

if [[ ${java_opts} == "" ]]; then
    java_opts="-Xms1G -Xmx1G -Xmn512M -Dserver.max-http-header-size=65536"
fi

release_user="root"


#projectdir
if [[ "${project_name}" == "easy-travel-netty" ]];then
    cib_s_package=${WORKSPACE}/target/*.jar
else    
    cib_s_package=${WORKSPACE}/${service_name}/${project_name}/target/*.jar
fi




#scp package
Scp_Pj(){
    release_ip=$1
    echo "==========scp $project_name to $release_ip============"
    echo "**********${service_name}***********"
    scp $cib_s_package $release_user@$release_ip:/data/target/
}

#log 
Log(){
    case ${1} in
        green)
            echo -e "\e[1;32m${2}\e[0m"
            ;;
        red)
            echo -e "\e[1;31m${2}\e[0m"
            ;;
        *)
            echo -e "${1}"
            ;;
    esac
}


#project start
Pj_Start(){
    release_ip=$1
    scp ${local_start_scripts}/${start_scripts} ${release_user}@${release_ip}:${remote_start_scripts_dir}/
    ssh ${release_user}@${release_ip} "sh ${remote_start_scripts_dir}/${start_scripts} ${project_name} ${type} ${java_opts}"
    if [ $? != 0 ];then
        Log red "${project_name} deploy failed" 
    else
        Log green "${project_name} deploy succeed"
    fi
}

Pj_Stop(){
    release_ip=$1
    scp ${local_start_scripts}/${start_scripts} ${release_user}@${release_ip}:${remote_start_scripts_dir}/
    ssh ${release_user}@${release_ip} "sh ${remote_start_scripts_dir}/${start_scripts} ${project_name} ${type}"
}


#mian funtion
case ${type} in
    start )
        release_ip_all=`echo $release_ip_all |sed -r 's/,/ /g'`
        arr=($release_ip_all)
        for ip in ${arr[@]}; do
            release_ip=`echo $ip |sed -r 's/"//g'`
            Log red "$release_ip"
            Scp_Pj $release_ip
            Pj_Start $release_ip
        done
    ;;
    stop )
        release_ip_all=`echo $release_ip_all |sed -r 's/,/ /g'`
        arr=($release_ip_all)
        for ip in ${arr[@]}; do
            release_ip=`echo $ip |sed -r 's/"//g'`
            Log red "$release_ip"
            Pj_Stop $release_ip
        done
    ;;
    * )
        Log red "New function to be developed..."
    ;;
esac



